package com.songcha.module_vip.ui.activity.vip_recharge

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import android.view.View.OnClickListener
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alipay.sdk.app.PayTask
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.songcha.library_base.mvvm.base.BaseMvvmActivity
import com.songcha.library_business.LibraryBusinessApplication
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.event.wx.WXPayRespEvent
import com.songcha.library_business.helper.WxHelper
import com.songcha.library_business.proxy.configuration.SystemConfigurationManager
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_business.util.BusinessJumpUtil
import com.songcha.library_common.helper.ViewHelper
import com.songcha.library_common.ui.dialog.CustomDialog
import com.songcha.library_common.util.GlideUtil
import com.songcha.library_common.util.StringUtil
import com.songcha.library_common.util.TimeUtil
import com.songcha.library_common.util.ToastUtil
import com.songcha.library_common.util.dp2px
import com.songcha.library_common.util.sp2px
import com.songcha.module_vip.R
import com.songcha.module_vip.bean.vip.CreateWxVipRechargeOrderDataBean
import com.songcha.module_vip.bean.vip.VipRechargePriceDataBean
import com.songcha.module_vip.databinding.VipActivityVipRechargeBinding
import com.songcha.module_vip.ui.adapter.VipRechargePriceAdapter
import com.songcha.module_vip.ui.dialog.CustomServiceDialog
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.util.concurrent.TimeUnit


@Route(path="/vip/VipRechargeActivity")
class VipRechargeActivity:BaseMvvmActivity<VipRechargeViewModel,VipActivityVipRechargeBinding>(),OnClickListener,OnItemClickListener {
    private var mAdapter:VipRechargePriceAdapter<VipActivityVipRechargeBinding>?=null

    companion object{
        const val SDK_ALIPAY = 1
    }

    override fun getLayoutId(): Int {
        return R.layout.vip_activity_vip_recharge
    }

    override fun isImmerseStatusBar(): Boolean {
        return true
    }

    override fun isNeedShowLoad(): Boolean {
        return true
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        if(FunctionConfig.IS_WX_PAY_ENABLED){
            viewModel.payType.value = 1
            ViewHelper.setVisibility(true,databinding.vipFlWxpay)
        }else{
            viewModel.payType.value = 2
            ViewHelper.setVisibility(false,databinding.vipFlWxpay)
        }

        databinding.vipCclRecharge.setOnClickListener(this)
        databinding.vipCclWxpay.setOnClickListener(this)
        databinding.vipCclAlipay.setOnClickListener(this)
        databinding.vipTvProtocol.setOnClickListener(this)


        databinding.vipHbv.addTextButton("客服",14f,Color.WHITE,14.dp2px()){
            SystemConfigurationManager.getSystemConfiguration()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    val dialog = CustomServiceDialog(this@VipRechargeActivity)
                    dialog.setCustomService(it.customerService)
                    dialog.show()
                },{

                })
        }

        EventBus.getDefault().register(this)
    }


    override fun initObserver() {
        viewModel.createWxVipRechargeOrderBean.observe(this){data->
            wxpay(data)
        }

        viewModel.createAlipayVipRechargeOrderInfo.observe(this){data->
            alipay(data.body)
        }

        viewModel.currentVipPrice.observe(this){data->
            databinding.vipTvRechargePrice.text= StringUtil.float2PlainString(data)
        }

        viewModel.createVipRechargeOrderState.observe(this){data->
            hideLoadingDialog()
        }

        viewModel.vipRechargePriceBean.observe(this){data->
            //val firstPrice=data.openVipList[0].firstMoney
            //val originPrice=data.openVipList[0].ordinaryMoney
            //databinding.vipTvExplain.text="首次开通${StringUtil.float2PlainString(firstPrice)}元/月，后续开通${StringUtil.float2PlainString(originPrice)}元/月"
            initRcv(data.first,data.openVipList)
        }

        viewModel.payType.observe(this){data->
            if(data==1){
                databinding.vipCclWxpay.apply {
                    setBorder(Color.parseColor("#EDB407"),0.5f.dp2px())
                    setContainerBackgroundColor(Color.parseColor("#26EDB407"))
                }
                databinding.vipCclAlipay.apply {
                    setBorder(Color.parseColor("#E1DAE8"),0.5f.dp2px())
                    setContainerBackgroundColor(Color.WHITE)
                }
                databinding.vipIvSelectWxpay.visibility=View.VISIBLE
                databinding.vipIvSelectAlipay.visibility=View.GONE
            }else{
                databinding.vipCclWxpay.apply {
                    setBorder(Color.parseColor("#E1DAE8"),0.5f.dp2px())
                    setContainerBackgroundColor(Color.WHITE)
                }
                databinding.vipCclAlipay.apply {
                    setBorder(Color.parseColor("#EDB407"),0.5f.dp2px())
                    setContainerBackgroundColor(Color.parseColor("#26EDB407"))
                }
                databinding.vipIvSelectWxpay.visibility=View.GONE
                databinding.vipIvSelectAlipay.visibility=View.VISIBLE
            }
        }

        viewModel.orderPayStatus.observe(this) { data ->
            hideLoadingDialog()
            showPayResultDialog(data)
        }
    }

    private fun showPayResultDialog(status:Int){
        if(status==0){
            val db=CustomDialog.Companion.Builder(this@VipRechargeActivity)
            db.setCancelText("")
                .setDialogMsg("中途取消支付")
                .setOnConfirmListener {
                    true
                }.create().show()
        } else if (status == 2) {

            onGetData()
            val db=CustomDialog.Companion.Builder(this@VipRechargeActivity)
            db.setCancelText("")
                .setDialogMsg("支付成功")
                .setOnConfirmListener {
                    this@VipRechargeActivity.finish()
                    true
                }.create().show()
        } else {
            val db=CustomDialog.Companion.Builder(this@VipRechargeActivity)
            db.setCancelText("")
                .setDialogMsg("支付失败")
                .setOnConfirmListener {
                    true
                }.create().show()
        }
    }

    private fun showUserInfo(){
        if(UserInfoManager.checkLogin()){
            databinding.vipTvNickName.text=UserInfoManager.userInfo!!.userNick
            GlideUtil.loadNetImage(databinding.vipIvAvatar,UserInfoManager.userInfo!!.avatar)
            if(UserInfoManager.isVip()){
                databinding.vipIvVip.visibility=View.VISIBLE
                databinding.vipCclNovip.visibility=View.GONE
                databinding.vipTvVipStatus.visibility=View.VISIBLE
                databinding.vipTvVipStatus.text="有效期至"+ TimeUtil.formatTimeYYYYMMDD(UserInfoManager.vipValidateTime)
                //databinding.vipTvVipStatus.text="有效期至"+ TimeUtil.formatTimeYYYYMMDD(UserInfoManager.vipValidateTime)
            }else{
                databinding.vipIvVip.visibility=View.GONE
                databinding.vipCclNovip.visibility=View.VISIBLE
                databinding.vipTvVipStatus.visibility=View.GONE
            }
        }else{
            databinding.vipTvNickName.text="游客"
            databinding.vipIvAvatar.setImageResource(com.songcha.library_business.R.mipmap.business_icon_avatar_nologin)
            databinding.vipIvVip.visibility=View.GONE
            databinding.vipCclNovip.visibility=View.VISIBLE
            databinding.vipTvVipStatus.visibility=View.GONE
        }

    }

    private fun initRcv(isFirst: Boolean,list:MutableList<VipRechargePriceDataBean.VipRechargePriceBean.OpenVipBean>) {
        databinding.vipRcvVip.apply {
            layoutManager=LinearLayoutManager(this@VipRechargeActivity,RecyclerView.HORIZONTAL,false)
            mAdapter=VipRechargePriceAdapter(isFirst,list)
            mAdapter!!.setOnItemClickListener(this@VipRechargeActivity)
            adapter=mAdapter

        }
    }

    override fun onGetData() {
        viewModel.getVipRechargePriceList()
        showUserInfo()
    }

    //invoke wxpay
    private fun wxpay(bean: CreateWxVipRechargeOrderDataBean.CreateWxVipRechargeOrderPayBean.CreateWxVipRechargeOrderBean){
        WxHelper.sendReq(bean.appid,bean.partnerId,bean.prepayId,bean.nonceStr,bean.timestamp,bean.sign,bean.packageVal)
    }


    private var mAlipayHandler=object :Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            if(msg.what==SDK_ALIPAY){
                val data=msg.obj as HashMap<String,String>
                onAlipay(data)
            }
        }
    }

    //invoke alipay
    private fun alipay(orderInfo:String){
        if(orderInfo.isBlank()) return
        val payRunnable = Runnable {
            val alipay = PayTask(this)
            val result = alipay.payV2(orderInfo, true)
            val msg = Message()
            msg.what = SDK_ALIPAY
            msg.obj = result
            mAlipayHandler.sendMessage(msg)
        }
        // must invoke by async
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    override fun isNeedShowLoadingDialog(): Boolean {
        return true
    }

    @Subscribe
    fun onWxPayEvent(event: WXPayRespEvent) {
        if (event.errCode == 0) {

        } else if (event.errCode == -2) {
            ToastUtil.show("中途取消支付")
            viewModel.setIsPaying(false)
        } else {
            ToastUtil.show("支付异常")
            viewModel.setIsPaying(false)
        }
    }

    private fun onAlipay(map:HashMap<String,String>){
        val resultStatus = map["resultStatus"]
        val result = map["result"]
        val memo = map["memo"]
        if(resultStatus == "9000"){
            if(viewModel.isPaying.value!! && (viewModel.payType.value!!) == 2){
                showLoadingDialog()
                Observable.just("")
                    .delay(2, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe{
                        viewModel.queryVipRechargeOrderState()
                    }
            }
        } else if(resultStatus == "6001"){
            ToastUtil.show("中途取消支付")
            viewModel.setIsPaying(false)
        }else{
            ToastUtil.show("支付异常")
            viewModel.setIsPaying(false)
        }
    }

    //wxpay cannot listen pay result if app back by background,so need to query order state on onresume
    override fun onResume() {
        super.onResume()
        if(viewModel.isPaying.value!! && (viewModel.payType.value!!)==1){
            showLoadingDialog()
            Observable.just("")
                .delay(2, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe{
                    viewModel.queryVipRechargeOrderState()
                }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.vip_ccl_wxpay->{
                if(viewModel.isPaying.value!!) return
                viewModel.setPayType(1)
            }
            R.id.vip_ccl_alipay->{
                if(viewModel.isPaying.value!!) return
                viewModel.setPayType(2)
            }
            R.id.vip_ccl_recharge->{
                if(!databinding.vipCcbRecharge.isCheck()){
                    ToastUtil.show("请勾选同意《vip服务协议》")
                    return
                }
                if(viewModel.isPaying.value!!) return
                if(UserInfoManager.checkJumpLogin()){
                    if(mAdapter==null || viewModel.vipRechargePriceBean.value==null) return

                    val item=viewModel.vipRechargePriceBean.value!!.openVipList[mAdapter!!.selectIndex]
                    var id=item.ordinaryId
                    if(viewModel.vipRechargePriceBean.value!!.first && item.firstMoney>0f){
                        id=item.firstId
                    }
                    if(viewModel.payType.value==1){
                        if(!WxHelper.checkWxInstalled()) return
                        showLoadingDialog(true)
                        viewModel.createVipRechargeOrderWx(id)
                    }else{
                        showLoadingDialog(true)
                        viewModel.createVipRechargeOrderAlipay(id)
                    }
                }
            }
            R.id.vip_tv_protocol->{
                SystemConfigurationManager.getSystemConfiguration()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({
                        if(it.vipProtocol!=null)
                            BusinessJumpUtil.toWebViewActivity(v.context,it.vipProtocol)
                    },{

                    })
            }
        }
    }



    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        if(mAdapter==null) return
        mAdapter!!.selectIndex=position
        mAdapter!!.notifyDataSetChanged()
        viewModel.setCurrentPrice(position)

    }


}